using System.Collections.Generic;
using DL.Tools;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace DL.UI
{
    //对于子类UI物体的一个接口
    //有新的绑定方案
    public abstract class ItemContent
    {
        private Button MyBtn;//这个上下文控制的Btn
        public UnityAction OnSelect;
        private GameObject item;
        protected ItemContent(GameObject item)
        {
            this.item = item;
            var btn = item.GetComponent<Button>();
            //必须注册Button进来
            if(btn == null) Debugger.EO_LogError("Button上下文错误");
            MyBtn = btn;
            MyBtn.onClick.AddListener(ItemClick);
        }

        private void ItemClick()
        {
            OnSelect?.Invoke();
            Click();
        }

        public virtual void Click()
        {
            
        }

        ~ItemContent()
        {
            MyBtn.onClick.RemoveListener(ItemClick);
        }

        public GameObject Go => item;
        
        //销毁时调用的方法，不要直接在list中删除
        public void Destroy<T>(List<T> list) where T: ItemContent
        {
            Object.DestroyImmediate(item);
            list.Remove(this as T);
            
            //对所有的Item进行排名序列更新  
            int idx = 0;
            list.ForEach(x =>
            {
                x.Go.name = string.Format("{0}_{1}", typeof(T).Name, idx++);
            });
            
        }
    }
}